package com.alibaba.wallstreet.uitls;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 类FtpClientUtil.java的实现描述：ftps的通用操作类
 * @author laijia.dlj 2015年8月19日 下午12:27:25
 */
public class FtpClientUtil {

    private static final Logger                  logger           = LoggerFactory.getLogger(FtpClientUtil.class);

    
    /**
     * 获取ftp连接
     * @param host
     * @param port
     * @param loginName
     * @param password
     * @param prototal
     * @param workDir
     * @return
     */
    public static FtpClient connectFtp(String host, int port, String loginName, String password, String prototal, String workDir) {
        try {   
            logger.info("Begin to connect to {}:{}, {}", new Object[] { host, port, loginName });
            FtpClient ftpClient = new FtpClient(host, port, prototal);
            ftpClient.connect();
            ftpClient.login(loginName, password);
            // 使用PROT P来传输数据
            ftpClient.protWithP();
            // 使用被动模式
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkdingDirectory(workDir);
            logger.info("Connect success with local port : {}", ftpClient.getLocalPort());     
            return ftpClient;
        } catch (Exception e) {
            logger.info("Connect ftp fail  {}:{}, {}", new Object[] { host, port, loginName }, e);  
            return null;
        }
    }

    
    /**
     * 释放连接
     * @param ftpClient
     */
    public static void disConnectFtp(FtpClient ftpClient) {
        if (ftpClient != null) {
            logger.info("Try to dis connent, local port : " + ftpClient.getLocalPort());
            logger.info("begin to do ftpClient quit");
            
            ftpClient.quit();
            
            logger.info("done ftpClient quit");
            logger.info("begin to do ftpClient disConnect");
            
            ftpClient.disConnect();
            logger.info("done ftpClient disConnect");
            ftpClient = null;
        }
    }
    
    
    
}
